package demo.customize;

import demo.configs.CustomizeConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.net.URI;

@Slf4j
@Service
public class CustomizeGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomizeConfig> implements Ordered {

    public CustomizeGatewayFilterFactory() {
        super(CustomizeConfig.class);
    }

    @Override
    public GatewayFilter apply(CustomizeConfig config) {
        return  ((exchange, chain) -> {
            log.info("request url" + exchange.getRequest().getURI() + "  " + config.toString());
//            return exchange.getResponse().setComplete();// 拒绝
            return chain.filter(exchange).then(Mono.defer(() -> {
                //这样获取到的是原来的url，因为这个ServerHttpRequest是不可以修改的，要获取到最后的url需要重新获取到ServerHttpRequest对象
                log.info("end origin: {}", exchange.getRequest().getURI());
                URI routedUri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
                log.info("end routed: {}", routedUri);
                return Mono.empty();
            }));
        });
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
